package com.hankol.feature_wine_meal

import android.view.View
import android.widget.TextView
import androidx.lifecycle.Observer
import com.baselibrary.Constants
import com.baselibrary.MessageBus
import com.baselibrary.activity.BaseFragment
import com.baselibrary.extension.checkNotNull
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.ARouterUtils
import com.baselibrary.utils.CommonUtil
import com.baselibrary.utils.NumberUtils
import com.baselibrary.view.SpaceItemDecoration
import com.baselibrary.utils.EmptyViewUtil
import com.hankol.feature_wine_meal.adapter.HotFoodMenuAdapter
import com.hankol.feature_wine_meal.bean.FoodDetailsBean
import com.hankol.feature_wine_meal.databinding.FragmentWineFoodBinding
import com.hankol.feature_wine_meal.viewmodel.WineFoodViewModel
import com.like.LikeButton
import com.like.OnLikeListener
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class HomeWineFoodFragment : BaseFragment(), WineFoodViewModel.OnBannerLooperListener, OnLikeListener {
    private lateinit var mViewModel: WineFoodViewModel
    private lateinit var mDataBinding: FragmentWineFoodBinding
    private val mAdapter by lazy { HotFoodMenuAdapter(mViewModel) }
    private var pagerNum: Int = 1
    private var clickView: View? = null
    private var clickData: FoodDetailsBean? = null

    companion object {
        @JvmStatic fun newInstance() = HomeWineFoodFragment().apply {}
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_wine_food
    }

    override fun init() {
        mDataBinding = getDataBinding<FragmentWineFoodBinding>()
        mViewModel = getFragmentViewModelProvider(this).get(WineFoodViewModel::class.java)
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        mDataBinding.rvWineFood.adapter = mAdapter
        mDataBinding.rvWineFood.addItemDecoration(SpaceItemDecoration(CommonUtil.dip2px(requireContext(), 4f)))
        mDataBinding.wfhWineFood.setFragmentManager(childFragmentManager)
        initListener()
        intObserve()
        loadData()
        mViewModel.startBannerLooper()
    }

    private fun loadData() {
        mViewModel.reqCharacteristic()
        mViewModel.reqFoodRecommend()
        mViewModel.reqHotFood(pagerNum)
    }

    private fun intObserve() {
        mViewModel.characteristicLD.observe(this, Observer {
            it?.let {
                mDataBinding.wfhWineFood.setCharacteristic(it)
            }
        })
        mViewModel.hotFoodLD.observe(this, Observer { it ->
            mDataBinding.smartWineFoodHome.finishLoadMore()
            mDataBinding.smartWineFoodHome.finishRefresh()
            if (pagerNum <= 1) {
                if (it.data.isNullOrEmpty()) {
                    //缺省页
                    mAdapter.setNewData(it.data)//如果不添加空集合，setEmptyView 就会报错
                    mAdapter.emptyView = EmptyViewUtil.getEmptyView(Constants.TYPE_WINE_MEAL, mDataBinding.rvWineFood, "暂无相关信息")
                } else {
                    mAdapter.setNewData(it.data)
                    pagerNum++
                }
            } else {
                it.data?.let {
                    if (it.isNotEmpty()) {
                        mAdapter.addData(it)
                        pagerNum++
                    }
                }

            }
        })

        mViewModel.recommendFoodLD.observe(this, Observer {
            mDataBinding.wfhWineFood.setRecommend(it)

        })

    }

    private fun initListener() {
        mViewModel.setOnBannerLooperListener(this)
        mAdapter.setOnItemClickListener { adapter, view, position ->
            val bean = adapter.data[position]
            if (bean is FoodDetailsBean) {
                clickView = view
                clickData = bean
                val hashMap: HashMap<String, Any> = hashMapOf()
                hashMap["DRINK_FOOD_PLATE_NAME"] = "热门菜谱"
                hashMap["CLASS_NAME"] = ""
                hashMap["RECOMMEND_NAME"] = "热门菜谱"
                hashMap[Constants.WINE_MEAL_DETAILS_ID] = bean.id
                ARouterUtils.jump(ActivityRouter.WINE_MEAL.WINE_MEAL_DETAILS, hashMap)
            }
        }
        mDataBinding.smartWineFoodHome.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                pagerNum = 1
                loadData()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                mViewModel.reqHotFood(pagerNum)
            }

        })
    }


    override fun onBannerLooper() {
        //
    }

    override fun liked(likeButton: LikeButton?) {

    }

    override fun unLiked(likeButton: LikeButton?) {

    }

    //EventBus 接受方法
    @Subscribe(threadMode = ThreadMode.MAIN) fun onEvent(messageBus: MessageBus) {
        when (messageBus.codeType) {
            MessageBus.msgId_wine_meal_like_true -> {
                clickData?.let {
                    //不是收藏状态，才去做操作
                    if (it.hasLiked != 1) {
                        it.hasLiked = 1
                        it.supportNum = it.supportNum.plus(1)
                        clickView?.findViewById<LikeButton>(R.id.iv_hot_give)?.isLiked = true
                        clickView?.findViewById<TextView>(R.id.iv_hot_giveNum)?.text = NumberUtils.formatBigNum(it.supportNum.toString())
                    }
                }
            }

            MessageBus.msgId_wine_meal_like_false -> {
                clickData?.let {
                    //收藏状态，才去做操作
                    if (it.hasLiked == 1) {
                        it.hasLiked = 0
                        it.supportNum = it.supportNum.minus(1)
                        if (it.supportNum < 0) {
                            it.supportNum = 0
                        }
                        clickView?.findViewById<LikeButton>(R.id.iv_hot_give)?.isLiked = false
                        clickView?.findViewById<TextView>(R.id.iv_hot_giveNum)?.text = NumberUtils.formatBigNum(it.supportNum.toString())
                    }
                }
            }
        }
    }

    override fun onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        super.onDestroy()
    }

}